
#import "JsonRpcRequest.h"

@implementation JsonRpcRequest

//
// next id
//
static NSInteger nextRequestId												= 1;

//
// method
//
@synthesize methodName														= _methodName;

//
// parameter list
//
@synthesize parameterList													= _parameterList;

//
// request id
//
@synthesize requestId														= _requestId;

//
// result
//
@synthesize result															= _result;

//
// init with method
//
- (id)initWithMethod:(NSString*)methodName
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	//
	// setup method,id
	//
	self.methodName															= methodName;
	self.parameterList														= [NSMutableArray array];
	_requestId																= nextRequestId ++;
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.methodName															= nil;
	self.parameterList														= nil;
	self.result																= nil;
	
	[super dealloc];
}

//
// add parameter
//
- (void)addParameter:(id)parameter
{
	[self.parameterList addObject:parameter];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// call super
	//
	[super setupRequest];
	
	//
	// setup post data
	//
	NSMutableDictionary* jsonDictionary										= [NSMutableDictionary dictionaryWithCapacity:3];
	[jsonDictionary setValue:self.methodName forKey:@"method"];
	[jsonDictionary setValue:self.parameterList forKey:@"params"];
	[jsonDictionary setValue:[NSNumber numberWithInteger:self.requestId] forKey:@"id"];
	NSError* error															= nil;
	self.postData															= [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
	self.error																= error;
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	if(self.response.statusCode == 200)
	{
		//
		// decode result
		//
		NSError* error														= nil;
		NSDictionary* jsonDictionary										= [NSJSONSerialization JSONObjectWithData:self.dataBuffer options:kNilOptions error:&error];
		self.error															= error;
		
		if([jsonDictionary isKindOfClass:[NSDictionary class]])
		{
			NSDictionary* error												= [jsonDictionary valueForKey:@"error"];
			if(error && [error isKindOfClass:[NSDictionary class]])
				[self setErrorMessage:[error valueForKey:@"message"] code:[[error valueForKey:@"code"] integerValue] domain:@"JsonRpcErrorDomain"];
			else
				self.result													= [jsonDictionary valueForKey:@"result"];
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

@end
